1768D - Lucky Permutation - CodeForces Solution


constructive algorithms dfs and similar graphs greedy *1800

Please click on ads to support us..

C++ Code:

#include<bits/stdc++.h>
using namespace std;
#define int long long
#define fastio() ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL)
#define MOD 998244353
#define INF 1e18
#define db(...) __f(#__VA_ARGS__, __VA_ARGS__);

template <typename Arg1>
void __f(const char* name, Arg1&& arg1) { cout << name << " : " << arg1 << '\n'; }
template <typename Arg1, typename... Args>
void __f(const char* names, Arg1&& arg1, Args&&... args) {
	const char* comma = strchr(names + 1, ',');
	cout.write(names, comma - names) << " : " << arg1 << " | "; __f(comma + 1, args...);
}
void __f(const char* name, vector<int> &a) { cout << name << " : "; for (auto v : a) cout << v << " "; cout << "\n";}

void solve() {
	int n;
	cin >> n;
	vector<vector<int>> g(n + 1);
	for (int i = 1; i <= n; ++i) {
		int x; cin >> x;
		g[i].push_back(x);
		g[x].push_back(i);
	}
	vector<int> vis(n + 1), s(n + 1);
	auto dfs = [&](int src, int id, int &sz, auto && dfs) -> void{
		vis[src] = id;
		sz++;
		for (auto ch : g[src]) {
			if (!vis[ch]) {
				dfs(ch, id, sz, dfs);
			}
		}
		s[src] = sz;
	};
	int id = 1, res = 0, ans = INF;
	for (int i = 1; i <= n; ++i) if (!vis[i]) {
			int sz = 0;
			dfs(i, id++, sz, dfs);
			res += sz - 1;
		}
	for (int i = 1; i < n; ++i) {
		if (vis[i] != vis[i + 1]) ans = min(ans, res + 1);
		else ans = min(ans, res - 1);
	}
	cout << ans;
}

int32_t main()
{
	fastio();
	int t = 1;
	cin >> t;
	while (t--) {
		solve();
		cout << "\n";
	}
	return 0;
}


Comments

Submit
0 Comments
More Questions

1688. Count of Matches in Tournament
1684. Count the Number of Consistent Strings
1588. Sum of All Odd Length Subarrays
1662. Check If Two String Arrays are Equivalent
1832. Check if the Sentence Is Pangram
1678. Goal Parser Interpretation
1389. Create Target Array in the Given Order
1313. Decompress Run-Length Encoded List
1281. Subtract the Product and Sum of Digits of an Integer
1342. Number of Steps to Reduce a Number to Zero
1528. Shuffle String
1365. How Many Numbers Are Smaller Than the Current Number
771. Jewels and Stones
1512. Number of Good Pairs
672. Richest Customer Wealth
1470. Shuffle the Array
1431. Kids With the Greatest Number of Candies
1480. Running Sum of 1d Array
682. Baseball Game
496. Next Greater Element I
232. Implement Queue using Stacks
844. Backspace String Compare
20. Valid Parentheses
746. Min Cost Climbing Stairs
392. Is Subsequence
70. Climbing Stairs
53. Maximum Subarray
1527A. And Then There Were K
1689. Partitioning Into Minimum Number Of Deci-Binary Numbers
318. Maximum Product of Word Lengths